package com.longteng.diamond.controller;

import com.longteng.diamond.domain.User;
import com.longteng.diamond.po.RequestResult;
import com.longteng.diamond.service.UserService;
import com.longteng.diamond.util.ValidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * Created by Administrator
 * DATE : 2018/7/5
 * TIME : 20:58
 * PROJECT : java-lesson
 * PACKAGE : com.longteng.lesson
 *
 * @author <a href="mailto:taki@qq.com">Administrator</a>
 */
@Controller
@SessionAttributes(value = {"user"})
@RequestMapping("/loginController")
public class LoginController {
    @Autowired
    ValidUtil validUtil;
    @Autowired
    UserService userService;
    @RequestMapping("/loginSystem")
    public ModelAndView loginSystem(@Valid User user, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView();
        if (!validUtil.checkParam(user.getClass().getDeclaredFields(), bindingResult, modelAndView)) {
            modelAndView.setViewName("page/login/loginPage");
            return modelAndView;
        }
        RequestResult requestResult = userService.checkUser(user);
        if (!requestResult.isSuccess()) {
            modelAndView.setViewName("page/login/loginPage");
            modelAndView.addObject("errorMsg", requestResult.getMsg());
            return modelAndView;
        }
        modelAndView.setViewName("redirect:/index");
        modelAndView.addObject("user", user);
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if (null != name && name.equalsIgnoreCase("JSESSIONID")) {
                cookie.setMaxAge(10000);
                cookie.setDomain("127.0.0.1");
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
        return modelAndView;
    }

    @RequestMapping("/loginOut")
    public ModelAndView loginOut(SessionStatus status) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:/loginPage");
        status.setComplete();
        return modelAndView;
    }

    @RequestMapping("/loginPage")
    public String login() {
        return "page/login/loginPage";
    }

}
